<?php
use Think\Mpage;


/**
 * 数据分页/列表显示
 * @param $count
 * @param $pageSize
 * @param $url
 * @param $p
 * @return string
 */
function listPage($count, $pageSize, $url, $p)
{
    $mpage = new Mpage($count, $pageSize, $url, $p);
    $mpage->style = [
        'div' => 'class="paginator" align="right"',
        "first" => 'class="ti first" data-value="%TIPAGE%" data-type="pagenum" rel="nofollow"',
        "last" => 'class="ti last" data-value="%TIPAGE%" data-type="pagenum" rel="nofollow"',
        "prev" => 'class="ti prev" data-value="%TIPAGE%" data-type="pagenum" rel="nofollow"',
        "next" => 'class="ti next" data-value="%TIPAGE%" data-type="pagenum" rel="nofollow"',
        "num" => 'class="ti" data-value="%TIPAGE%" data-type="pagenum" rel="nofollow"',
        "current" => 'class="this-page" rel="nofollow"',
    ];
    return $pageHtml = $mpage->show();
}

/**
 * 获取采集网站的域名
 * @param $cj_id
 * @return mixed
 */
function get_cj_site_name($cj_id){
    $data = M('CaijiRole')->field('name')->find($cj_id);
    $res = $data['name'];
    
    return $res;
}

/**
 * 返回文章采集规则
 * @param $cj_id
 * @return mixed
 */
function get_article_role($cj_id){
    $data = M('CaijiRole')->field('article_role')->find($cj_id);
    $res = unserialize($data['article_role']);

    return $res;
}

/**
 * 返回列表采集规则
 * @param $cj_id
 * @return mixed
 */
function get_list_role($cj_id){
    $data = M('CaijiRole')->field('list_role')->find($cj_id);
    $res = unserialize($data['list_role']);

    return $res;
}

/**
 * 获取输入编码
 * @param $cj_id
 * @return mixed
 */
function get_in_code($cj_id){
    $data = M('CaijiRole')->field('in_code')->find($cj_id);
    return $data['in_code'];
}

/**
 * 获取输出编码
 * @param $cj_id
 * @return mixed
 */
function get_out_code($cj_id){
    $data = M('CaijiRole')->field('list_role')->find($cj_id);
    return $data['out_code'];
}

/**
 * 获取站点目录
 * @param $site_id
 * @return string
 */
function get_site_dir_path($site_id = 0){
    $data = M('Site')->find($site_id);
    $sitePath = MAKE_SITE_PATH.$data['site'].'/';

    return $sitePath;
}


/**
 * 获取目录路径
 * @param $cid
 * @return mixed
 */
function get_category_dir_path($site_id = 0, $cid = 0){

    $cateInfo = D('Category')->find($cid);
    $sitePath = get_site_dir_path($site_id);
    $catePath = $sitePath.$cateInfo['dir'].'/';
    
    return $catePath;
}

/**
 * 获取分类目录名称 dir
 * @param int $site_id
 * @param int $cid
 * @return mixed
 */
function get_category_dir_name($site_id = 0, $cid = 0){
    $map = [
        'id' => $cid,
        'site_id' => $site_id,
    ];
    $cateInfo = D('Category')->where($map)->find();
    $cateName = $cateInfo['dir'];
    
    return $cateName;
}

/**
 * 获取分类名称 name
 * @param int $site_id
 * @param int $cid
 * @return mixed
 */
function get_category_cate_name($site_id = 0, $cid = 0){
    $map = [
        'id' => $cid,
        'site_id' => $site_id,
    ];
    $cateInfo = D('Category')->where($map)->find();
    $cateName = $cateInfo['name'];

    return $cateName;
}

/**
 * 翻译
 * @param $text
 * @return string
 */
function translation($text){

    $baseUrl = 'http://fanyi.youdao.com/translate';
    $fields = [
        'i'=>$text,
        'type'=>'AUTO',
        'doctype'=>'json',
    ];

    $cont = request_post($baseUrl,$fields);
    $data = json_decode($cont, true);
    
    $res = '';
    if($data["errorCode"]==0){
        $res = '';
        foreach($data["translateResult"] as $tr){
            foreach($tr as $td){
                $res .= $td['tgt'];
            }
        }
    }
    return $res;

}

/**
 * ajax 采集列表
 * @param string $url 请求的url
 * @param array $post_data 提交的数据
 * @return bool|mixed
 */
function request_post($url = '', $post_data = array()) {
    if (empty($url) || empty($post_data)) {
        return false;
    }

    $o = "";
    foreach ( $post_data as $k => $v )
    {
        $o.= "$k=" . urlencode( $v ). "&" ;
    }
    $post_data = substr($o,0,-1);

    $postUrl = $url;
    $curlPost = $post_data;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$postUrl);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}

/**
 * 生成html时获取文章的完整静态url
 * @param $art_id
 * @return string
 */
function get_article_url($art_id){
    $artInfo = M('Article')->find($art_id);
    $cateInfo = M('Category')->find($artInfo['cid']);
    $siteInfo = M('Site')->find($artInfo['site_id']);

    $path = $siteInfo['domain_name'].'/'.$cateInfo['dir'].'/'.'article_'.$art_id.'.html';

    return $path;
}

/**
 * 实时显示提示信息
 */
function showMsgHtml(){
    echo "<style>.red{color:red;}</style><div id='show-list' style='margin:0 auto; text-align:center;overflow:auto; max-height: 600px; /*border: 1px solid #999;*/' class='install-database'>".
            "<div style='position:fixed;/*width:100%;height:5px;border-top:1px solid gray;border-bottom:1px solid gray;*/'><div id='caiji-step' class='step' style='margin-left:20px;border-radius:50px;height:5px;background:#747474;'></div></div></div>".
             "<script type='text/javascript'>
                var list   = document.getElementById('show-list');
                function showmsg(msg, classname, step){
                    var li = document.createElement('p'); 
                    li.innerHTML = msg;
                    classname && li.setAttribute('class', classname);
                    list.appendChild(li);
                    document.scrollTop += 30;
                    list.scrollTop = list.scrollHeight;
                    st = document.getElementById('caiji-step');
                    st.style.width = parseInt(list.offsetWidth - list.offsetWidth/step) + 'px';
                    console.log(st.style.width);
                }
             </script>";
}

/**
 * 实时显示提示信息
 * @param  string $msg 提示信息
 * @param  string $class 输出样式（success:成功，error:失败）
 * @author huajie <banhuajie@163.com>
 */
function showMsg($msg, $class = '', $step){
    echo "<script type=\"text/javascript\">showmsg(\"{$msg}\",\"{$class}\",\"{$step}\")</script>";
    flush();
    ob_flush();
}

/**
 * 中文字符串截取
 * @param $str
 * @param int $start
 * @param $length
 * @param bool $suffix
 * @param string $charset
 * @return string
 */
function msubstr($str, $start=0, $length, $suffix=true, $charset="utf-8"){
    if(mb_strlen($str,$charset)>$length)
    {
        if(function_exists("mb_substr")){
            if($suffix)
                return mb_substr($str, $start, $length, $charset)."...";
            else
                return mb_substr($str, $start, $length, $charset);
        }elseif(function_exists('iconv_substr')) {
            if($suffix)
                return iconv_substr($str,$start,$length,$charset)."...";
            else
                return iconv_substr($str,$start,$length,$charset);
        }
        $re['utf-8'] = "/[x01-x7f]|[xc2-xdf][x80-xbf]|[xe0-xef][x80-xbf]{2}|[xf0-xff][x80-xbf]{3}/";
        $re['gb2312'] = "/[x01-x7f]|[xb0-xf7][xa0-xfe]/";
        $re['gbk'] = "/[x01-x7f]|[x81-xfe][x40-xfe]/";
        $re['big5'] = "/[x01-x7f]|[x81-xfe]([x40-x7e]|xa1-xfe])/";
        preg_match_all($re[$charset], $str, $match);
        $slice = join("",array_slice($match[0], $start, $length));
        if($suffix) return $slice."…";
        return $slice;
    }
    else
    {
        return $str;
    }
}

/**
 * 获取友情链接
 * @param int $site_id
 * @param int $num
 * @return mixed
 */
function get_flinks($site_id = 0, $num = 10) {

    $map['status'] = 1;
    if($site_id){
        $map['site_id'] = $site_id;
    }
    $linkData = M('Flink')->where('status = 1')->order('sort DESC')->limit($num)->select();

    return $linkData;
}

/**
 * 获取网站SEO 关键词/描述
 * @param $url
 * @return array
 */
function get_keywords_description($url) {
    $res = get_meta_tags($url);
    if($res['keywords'] == NULL){
        $res['keywords'] = $res['news_keywords'];
    }
    return $res;
}

/**
 * Todo 废弃 
 * 使用cURL获取一个网页中的 keyword 和 description 部分
 * 加载很费时，不采用
 * @param str $ 查询的url地址
 * @return array array('keyword'=>keyword部分,'description'=>description部分)
 */
function curl_getkd($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $html = curl_exec($ch);
    $info = curl_getinfo($ch);
    if ($html === false) {
        echo "cURL Error: " . curl_error($ch);
    }
    curl_close($ch);
    preg_match_all("/<meta[^>]+name=\"([^\"]*)\"[^>]" . "+content=\"([^\"]*)\"[^>]*>/i", $html, $r, PREG_PATTERN_ORDER);

    for ($i = 0;$i < count($r[1]);$i++) {
        if (strtolower($r[1][$i]) == "keywords") $meta['keywords'] = $r[2][$i];
        if (strtolower($r[1][$i]) == "description") $meta['description'] = $r[2][$i];
    }

    if($meta['keywords'] == NULL){
        $meta['keywords'] = $meta['news_keywords'];
    }
    return $meta;
}

/**
 * 删除多余的回车换行
 * @param $html
 * @return mixed
 */
function del3br($html) {

    $br='';
    for($i=0;$i<3;$i++){
        $br.=chr(10);
    }
    $html=str_replace($br, '', $html);
    $html=str_replace(chr(32).chr(32).chr(32), '', $html);
    return $html;
}

/**
 * 链接带域名
 * @param $cj_id
 * @param $cj_iurl
 * @return string
 */
function link_with_domain($cj_id, $cj_url){

    $caijiUrlFirstStr = substr($cj_url, 0, 1 );
    if($caijiUrlFirstStr == '/'){
        $res = get_cj_site_name($cj_id).$cj_url;
    }else{
        $res = $cj_url;
    }
    
    return $res;
    
}

/**
 * 获取网站域名 如 vbao100.com
 * @param $url
 */
function get_domain($url){
    preg_match('/[\w][\w-]*\.(?:com\.cn|com|cn|co|net|org|gov|cc|biz|info)(\/|$)/isU', $url, $domain);
    return rtrim($domain[0], '/');
}

/**
 * 获取网站信息
 * @param $site_id
 * @return mixed
 */
function get_site_info($site_id){
    $data = M('Site')->find($site_id);
    
    return $data;
}

/**
 * 获取分类列表
 * @return mixed
 */
function get_cate_list($map = '')
{
    $data = M('Category')->where($map)->order('id ASC')->select();
    
    return $data;
}

/**
 * 获取分类信息
 * @param $cid
 * @return mixed
 */
function get_cate_info($cid)
{
    $data = M('Category')->find($cid);
    return $data;
}

/**
 * 时间戳格式化
 * @param int $time
 * @return string 完整的时间显示
 */
function time_format($time = NULL, $format = 'Y-m-d H:i')
{
    $time = $time === NULL ? NOW_TIME : intval($time);
    return date($format, $time);
}

/*计算当前时间与@param的距离 返回 秒 分 时 天 (前)
    * @param Time stamp
    * @return string
    */
function time_stamp($firstTime){
    $now=time();
    $data=$now-$firstTime;
    if($data < 60){
        $res=$data."秒前";
    }elseif($data > 60 && $data < 3600){
        $res=floor($data/60)."分钟前";
    }elseif ($data > 3600 && $data < 86400) {
        $res=floor($data/3600)."小时前";
    }else{
        $res=floor($data/86400)."天前";
    }
    return $res;
}

function strCut($cutStr, $str, $replace = '') {

    return str_replace($cutStr, $replace, $str);

}

/*
 * 从字符串中提取数字
 */
function getNumber($str){
    //价格只提取数字
    $reg='/\d+/';//匹配数字的正则表达式
    preg_match($reg, $str, $res);

    return $res[0];
}